package abq2.jic.jic.plugin.other.other.mob.mob;

import kd.bos.bill.AbstractMobBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.*;
import kd.bos.form.control.Button;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.CustomEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.plugin.AbstractMobFormPlugin;
import kd.bos.mvc.bill.MobileBillView;
import kd.bos.mvc.form.MobileFormView;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.LinkedHashMap;

public class BookMobBorrowSyncPlugin extends AbstractMobBillPlugIn {

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        addClickListeners("kdec_booksync");
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        if (evt.getSource() instanceof Button) {
            switch (((Button) evt.getSource()).getKey()) {
                case "kdec_booksync":
                    HashMap args = new HashMap();
                    // qr：二维码扫码框
                    // bar：条形码扫码框
                    args.put("type", "qr");
                    HashMap map = new HashMap();
                    map.put("method", "scanQRCode");
                    map.put("args", args);
                    this.getView().executeClientCommand("callAPPApi", map);
                    break;
            }
        }
    }

    @Override
    public void customEvent(CustomEventArgs e) {
        String eventName = e.getEventName();
        String content = e.getEventArgs();
        String key = e.getKey();
        if (key.equals("callAppMethod")) {

            if (eventName.equals("scanQRCode")) {
                //扫码处理逻辑
                HashMap mapBook = SerializationUtils.fromJsonString(content, HashMap.class);
                mapBook = SerializationUtils.fromJsonString(mapBook.get("qrcode_str").toString(), HashMap.class);

                String name = ((LinkedHashMap) mapBook.get("name")).get("zh_CN").toString();
                String status = mapBook.get("kdec_billstatusfield").toString();
                switch (status) {
                    case "A":
                        status = "可借阅";
                        break;
                    case "B":
                        status = "被预约";
                        break;
                    case "C":
                        status = "已借出";
                        break;
                    case "D":
                        status = "待上架";
                        break;
                }
                String author = mapBook.get("kdec_author").toString();
                String number = mapBook.get("number").toString();

                ConfirmCallBackListener confirmCallBacks = new ConfirmCallBackListener("SyncBorrowConfirm", this);

                getView().showConfirm("借阅书籍", "书名：" + name + "\n编号：" + number + "\n作者：" + author + "\n借阅状态：" + status,
                        MessageBoxOptions.OKCancel, ConfirmTypes.Default, confirmCallBacks, null, content);
            }
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        if (messageBoxClosedEvent.getResult().equals(MessageBoxResult.Yes)) {
            HashMap mapBook = SerializationUtils.fromJsonString(messageBoxClosedEvent.getCustomVaule(), HashMap.class);
            mapBook = SerializationUtils.fromJsonString(mapBook.get("qrcode_str").toString(), HashMap.class);

            // 获取当前借书单
            DynamicObject record = BusinessDataServiceHelper.loadSingle(getModel().getValue("id"), "kdec_borrowbook");

            // 新增单据体
            DynamicObjectCollection entryCollection = record.getDynamicObjectCollection("kdec_detail"); //获取单据体容器
            DynamicObject entry = new DynamicObject(entryCollection.getDynamicObjectType());    // 新增一行
            entry.set("kdec_bd_book", mapBook.get("id")); //要借的书
            entry.set("kdec_borrow_date", new Date());  //借书日期（今天）
            entry.set("kdec_deadline", new Date(System.currentTimeMillis() + 60 * 60 * 24 * 30 * 1000L));   // 最晚还书日期（30天后）
            entry.set("kdec_billstatusfield", "A");  //状态：待归还
            entry.set("kdec_qtyfield", 1);  // 申请数量
            entryCollection.add(entry);

            // 保存record对象
            OperationResult borrowResult = SaveServiceHelper.saveOperate("kdec_borrowbook",
                    new DynamicObject[]{record}, OperateOption.create());

            // 更新书籍状态
            DynamicObject bookDynamicObject = BusinessDataServiceHelper.loadSingle(mapBook.get("id"), "kdec_book_all");
            bookDynamicObject.set("kdec_billstatusfield", "C");
            OperationResult bookResult = SaveServiceHelper.saveOperate("kdec_book_all",
                    new DynamicObject[]{bookDynamicObject}, OperateOption.create());

            getView().showSuccessNotification("借阅成功");
            getView().invokeOperation("refresh");
        }
    }


}
